<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/19 0019
 * Time: 13:20
 */

namespace Modules;

use Admin\Models\lm\XHLmGoods;
use Admin\Models\lm\XHLmGoodsIn;
use Admin\Models\lm\XHLmGoodsOut;
use Admin\Models\lm\XHLmGoodsType;
use Helpers\XhException;
use Phalcon\Mvc\Model\Transaction\Manager as TxManager;
use Phalcon\Di;

class Lm
{

    /**
     * 物品入库接口
     *
     * @param $params : ['id'物品id, 'time'入库时间, 'num'数量, 'type'登记或归还, 'userId'入库人, 'status'正常或报废] 必填，
     * [price采购价,remark备注, size规格, inTypeId入库类型关联Id, phoneNum手机卡手机号] 选填
     *
     * @return bool
     * @throws XhException
     *
     * create by qgz 20180719
     */
    public static function goodsInHandle($params = [])
    {
        if (empty($params)) {
            throw new XhException('参数为空');
        }
        //检查参数是否完整
        $mustArr = ['id', 'time', 'num', 'type', 'userId', 'status'];//必填项
        $keyArr  = array_keys($params);
        foreach ($mustArr as $key) {
            if (!in_array($key, $keyArr)) {
                throw new XhException('请传入完整参数');
            } else {
                if ($params[$key] == '' || $params[$key] == null) {
                    throw new XhException('参数错误');
                }
            }
        }
        $transaction = Di::getDefault()->get('db');
        $transaction->begin();
        $goodsInObj            = new XHLmGoodsIn();
        $goodsInObj->iGoodsId  = $params['id'];
        $goodsInObj->tInTime   = $params['time'];
        $goodsInObj->iInNum    = $params['num'];
        $goodsInObj->iInType   = $params['type'];
        $goodsInObj->iInUserId = $params['userId'];
        $goodsInObj->iInStatus = $params['status'];
        $goodsInObj->iInPrice  = isset($params['price']) ? $params['price'] : '';
        $goodsInObj->sSize     = isset($params['size']) ? $params['size'] : '';
        $goodsInObj->sRemark   = isset($params['remark']) ? $params['remark'] : '';
        $goodsInObj->sPhoneNum   = isset($params['phoneNum']) ? $params['phoneNum'] : '';
        if ($params['type'] != 1) {//归还记录关联id
            $goodsInObj->iInTypeId = isset($params['inTypeId']) ? $params['inTypeId'] : '';
        }
        if (isset($params['createUser'])) {
            $goodsInObj->iCreateUserId = $params['createUser'];
        }
        if (!$goodsInObj->save()) {
            $transaction->rollback();
            throw new XhException('保存记录失败');
        }
        $goodsData = XHLmGoods::findFirst([
            'conditions' => 'bDelete = 0 AND iId = :iId:',
            'bind'       => ['iId' => $params['id']]
        ]);
        if (!$goodsData) {
            $transaction->rollback();
            throw new XhException('暂无物品数据');
        }
        //计算库存和总数量
        $num = self::getNumData('in', $params['num'], $params['type'], $params['status'], $goodsData->iType);
        $goodsData->iNum    += $num['store'];
        $goodsData->iAllNum += $num['all'];
        if (!$goodsData->save()) {
            $transaction->rollback();
            throw new XhException('保存物品数量出错');
        }
        $transaction->commit();

        return true;
    }

    /**
     * 物品出库接口
     *
     * @param $params : ['id'物品id, 'time'出库时间, 'num'数量, 'type'登记或领取, 'userId'出库人, 'status'正常或报废] 必填，
     * [remark备注, size规格,outTypeId关联领用id，phoneNum手机卡手机号] 选填
     *
     * @return bool
     * @throws XhException
     *
     * create by qgz 20180719
     */
    public static function goodsOutHandle($params)
    {
        if (empty($params)) {
            throw new XhException('参数为空');
        }
        //检查参数是否完整
        $mustArr = ['id', 'time', 'num', 'type', 'userId', 'status'];//必填项
        $keyArr  = array_keys($params);
        foreach ($mustArr as $key) {
            if (!in_array($key, $keyArr)) {
                throw new XhException('请传入完整参数');
            } else {
                if ($params[$key] == '' || $params[$key] == null) {
                    throw new XhException('参数错误');
                }
            }
        }
        $transaction = Di::getDefault()->get('db');
        $transaction->begin();
        $goodsOutObj             = new XHLmGoodsOut();
        $goodsOutObj->iGoodsId   = $params['id'];
        $goodsOutObj->tOutTime   = $params['time'];
        $goodsOutObj->iOutNum    = $params['num'];
        $goodsOutObj->iOutType   = $params['type'];
        $goodsOutObj->iOutUserId = $params['userId'];
        $goodsOutObj->iOutStatus = $params['status'];
        $goodsOutObj->sSize      = isset($params['size']) ? $params['size'] : '';
        $goodsOutObj->sRemark    = isset($params['remark']) ? $params['remark'] : '';
        $goodsOutObj->sPhoneNum   = isset($params['phoneNum']) ? $params['phoneNum'] : '';
        if ($params['type'] != 1) {//领用记录关联领用id
            $goodsOutObj->iOutTypeId = isset($params['outTypeId']) ? $params['outTypeId'] : '';
        }
        if (isset($params['createUser'])) {
            $goodsOutObj->iCreateUserId = $params['createUser'];
        }
        if (!$goodsOutObj->save()) {
            $transaction->rollback();
            throw new XhException('保存记录失败');
        }
        $goodsData = XHLmGoods::findFirst([
            'conditions' => 'bDelete = 0 AND iId = :iId:',
            'bind'       => ['iId' => $params['id']]
        ]);
        if (!$goodsData) {
            $transaction->rollback();
            throw new XhException('暂无物品数据');
        }
        //计算库存和总数量
        $num = self::getNumData('out', $params['num'], $params['type'], $params['status'], $goodsData->iType);
        $goodsData->iNum    -= $num['store'];
        $goodsData->iAllNum -= $num['all'];
        if (!$goodsData->save()) {
            $transaction->rollback();
            throw new XhException('保存物品数量出错');
        }
        $transaction->commit();

        return true;
    }

    /**
     * 计算应添加或减少的库存和总数量
     *
     * @param null $inOrOut 入库或出库
     * @param null $data 数量
     * @param null $type 登记或归还
     * @param null $status 正常或报废
     * @param null $isConsume 是否消耗品
     *
     * @return array
     *
     * create by qgz 20180720
     */
    public static function getNumData($inOrOut = null, $data = null, $type = null, $status = null, $isConsume = null)
    {
        $return = ['store' => 0, 'all' => 0];
        if (empty($data) || $inOrOut === null) {
            return $return;
        }
        switch ($inOrOut) {
            case 'in'://入库
                if ($status == 0) {//正常
                    $return['store'] = $data;
                    if ($isConsume == 0) {//非消耗品
                        if ($type == 1) {//登记
                            $return['all'] = $data;
                        }
                    } elseif ($isConsume == 1) {//消耗品
                        $return['all'] = $data;
                    }
                } elseif ($status == 1) {//报废
                    if ($isConsume == 0) {//非消耗品
                        if ($type == 2) {//归还
                            $return['all'] = - $data;
                        }
                    }
                }
                break;
            case 'out'://出库
                $return['store'] = $data;
                if ($status == 0) {//正常
                    if ($isConsume == 1) {//消耗品
                        $return['all'] = $data;
                    }
                } elseif ($status == 1) {//报废
                    $return['all'] = $data;
                }
                break;
            default:
                break;
        }

        return $return;
    }

    /**
     * 根据UserId获取领用物品数据
     *
     * @param string $userId
     *
     * @return mixed
     * @throws XhException
     *
     * create by qgz 20181219
     */
    public static function getOutGoodsDataByUserId($userId = '')
    {
        if (!$userId) {
            throw new XhException("没有人员参数");
        }
        $data = Di::getDefault()->get('modelsManager')->createBuilder()
                  ->columns("a.iProdId as iGoodsId, b.sGoodsName, a.iNum as iOutNum, DATE_FORMAT(c.tRealTime,'%Y-%m-%d') as tOutTime, c.tApplyDate, a.sNumber, c.iReceiveId, CASE c.iState WHEN 0 THEN '待确认' WHEN 4 THEN '已领用' END as iState")
                  ->from(['a' => 'Admin\Models\ims\XHImsReceiveProds'])
                  ->leftjoin("Admin\Models\lm\XHLmGoods", 'a.iProdId = b.iId and b.bDelete = 0', 'b')
                  ->leftjoin("Admin\Models\ims\XHImsReceive", 'a.sNumber = c.sNumber and c.bDelete = 0', 'c')
                  ->where('a.bDelete = 0 and a.bReceive = 1 and b.bDelete = 0 and c.bDelete = 0 and c.iReceiveId = :iReceiveId:', ['iReceiveId' => $userId])
                  ->getQuery()
                  ->execute()->toArray();
        return $data;
    }

    /**
     * 根据UserId获取归还物品数据
     *
     * @param string $userId
     *
     * @return mixed
     * @throws XhException
     *
     * create by qgz 20180220
     */
    public static function getInGoodsDataByUserId($userId = '')
    {
        if (!$userId) {
            throw new XhException("没有人员参数");
        }
        $data = Di::getDefault()->get('modelsManager')->createBuilder()
                  ->columns("a.iProdId as iGoodsId, b.sGoodsName, a.iNum as iInNum, DATE_FORMAT(c.tRealTime,'%Y-%m-%d') as tInTime, c.tApplyDate, a.sNumber, c.iReturnId, CASE c.iState WHEN 0 THEN '待确认' WHEN 4 THEN '已归还' END as iState")
                  ->from(['a' => 'Admin\Models\ims\XHImsReceiveProds'])
                  ->leftjoin("Admin\Models\lm\XHLmGoods", 'a.iProdId = b.iId and b.bDelete = 0', 'b')
                  ->leftjoin("Admin\Models\ims\XHImsReturn", 'a.sNumber = c.sNumber and c.bDelete = 0', 'c')
                  ->where('a.bDelete = 0 and a.bReceive = 0 and b.bDelete = 0 and c.bDelete = 0 and c.iReturnId = :iReturnId:', ['iReturnId' => $userId])
                  ->getQuery()
                  ->execute()->toArray();
        return $data;
    }
}
